package com.snowj.apaas.service.impl;

import com.snowj.apaas.domain.auto.Clients;
import com.snowj.apaas.repository.auto.AgreementsDynamicSqlSupport;
import com.snowj.apaas.repository.auto.ClientsDynamicSqlSupport;
import com.snowj.apaas.repository.auto.ClientsMapper;
import com.snowj.apaas.security.SecurityConstants;
import com.snowj.apaas.security.SecurityUtils;
import com.snowj.apaas.service.ClientService;
import org.mybatis.dynamic.sql.where.condition.IsEqualTo;
import org.mybatis.dynamic.sql.where.condition.IsLike;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class ClientServiceImpl implements ClientService {

    private final ClientsMapper clientsMapper;

    public ClientServiceImpl(ClientsMapper clientsMapper) {
        this.clientsMapper = clientsMapper;
    }

    /**
     * 列出所有客户
     *
     * @return
     */
    @Override
    public List<Clients> listAllClients() {
        List<String> authorties = SecurityUtils.getCurrentUserAuthorties();
        return clientsMapper.select(c -> {
            // 添加权限信息
            if (!authorties.contains(SecurityConstants.ROLE_ADMIN)  && !authorties.contains(SecurityConstants.ROLE_ASSISTANT)) {
                String currentUser = SecurityUtils.getCurrentUserLogin();
                c.where(AgreementsDynamicSqlSupport.createdBy, IsEqualTo.of(() -> currentUser));
            }
            return c;
        });
    }

    /**
     * 列出客户列表
     *
     * @param name     客户名称
     * @param pageable
     * @return
     */
    @Override
    public Page<Clients> listClients(String name, Pageable pageable) {
        List<String> authorties = SecurityUtils.getCurrentUserAuthorties();
        List<Clients> clients = clientsMapper.select(c -> {
            // 添加权限信息
            if (!authorties.contains(SecurityConstants.ROLE_ADMIN)  && !authorties.contains(SecurityConstants.ROLE_ASSISTANT)) {
                String currentUser = SecurityUtils.getCurrentUserLogin();
                c.where(ClientsDynamicSqlSupport.createdBy, IsEqualTo.of(() -> currentUser));
            }
            if (!StringUtils.isEmpty(name)) {
                c.where(ClientsDynamicSqlSupport.name, IsLike.of(() -> "%" + name + "%"));
            }
            c.offset((long) pageable.getPageSize() * pageable.getPageNumber());
            return c.limit(pageable.getPageSize());
        });
        long total = clientsMapper.count(c -> {
            // 添加权限信息
            if (!authorties.contains(SecurityConstants.ROLE_ADMIN)  && !authorties.contains(SecurityConstants.ROLE_ASSISTANT)) {
                String currentUser = SecurityUtils.getCurrentUserLogin();
                c.where(ClientsDynamicSqlSupport.createdBy, IsEqualTo.of(() -> currentUser));
            }
            if (!StringUtils.isEmpty(name)) {
                c.where(ClientsDynamicSqlSupport.name, IsLike.of(() -> "%" + name + "%"));
            }
            return c;
        });
        return new PageImpl<>(clients, pageable, total);
    }

    /**
     * 根据id查找客户
     *
     * @param id 客户编号
     * @return
     */
    @Override
    public Optional<Clients> findClientById(Long id) {
        List<String> authorties = SecurityUtils.getCurrentUserAuthorties();
        // 添加权限信息
        if (!authorties.contains(SecurityConstants.ROLE_ADMIN)  && !authorties.contains(SecurityConstants.ROLE_ASSISTANT)) {
            return clientsMapper.selectOne(c -> {
                String currentUser = SecurityUtils.getCurrentUserLogin();
                c.where(ClientsDynamicSqlSupport.createdBy, IsEqualTo.of(() -> currentUser));
                c.where(ClientsDynamicSqlSupport.id, IsEqualTo.of(() -> id));
                return c;
            });
        } else {
            return clientsMapper.selectByPrimaryKey(id);
        }
    }

    /**
     * 创建客户
     *
     * @param clients 客户信息
     * @return
     */
    @Override
    public Clients createClient(Clients clients) {
        if (clients.getId() != null) {
            return null;
        }
        clients.setCreatedBy(SecurityUtils.getCurrentUserLogin());
        clients.setCreatedDate(new Date());
        clientsMapper.insert(clients);
        return clients;
    }

    /**
     * 更新客户信息
     *
     * @param clients 客户信息
     * @return
     */
    @Override
    public Clients updateClient(Clients clients) {
        if (clients.getId() == null) {
            return null;
        }
        Optional<Clients> savedClientOptional = clientsMapper.selectByPrimaryKey(clients.getId());
        if (savedClientOptional.isPresent()) {
            Clients savedClient = savedClientOptional.get();
            clients.setCreatedBy(savedClient.getCreatedBy());
            clients.setCreatedDate(savedClient.getCreatedDate());
            clients.setLastModifiedBy(SecurityUtils.getCurrentUserLogin());
            clients.setLastModifiedDate(new Date());
            clientsMapper.updateByPrimaryKey(clients);
            return clients;
        } else {
            return null;
        }
    }

    /**
     * 删除客户
     *
     * @param id 客户编号
     */
    @Override
    public void deleteClient(Long id) {
        clientsMapper.deleteByPrimaryKey(id);
    }
}
